import router from '@/router'
import { defineStore } from 'pinia'
import { cloneDeep } from 'lodash-es'
import { constantMenuRoutes } from '@/router/modules/staticMenu'

// 获取视图模板
const modules = import.meta.glob('@/views/**/*.vue')

export const useRouteStore = defineStore(
  'routes',
  () => {
    const routeData = ref<Routes.RouterListItem[]>([])
    const isGetRouter = ref<boolean>(false)
    const menuList = ref<Routes.RouterListItem[]>([])

    // 格式化路由信息
    const formatRoutes = (routes: Routes.RouterListItem[] = []): Routes.RouterListItem[] => {
      return routes.map((routeItem: Routes.RouterListItem) => {
        routeItem.component = modules[`/src/views/${routeItem.component}`]
        if (routeItem.children) {
          routeItem.children = formatRoutes(routeItem.children)
        }
        return routeItem
      })
    }

    // 设置路由信息
    const setRoutes = (routes: Routes.RouterListItem[] = [], isfirst: boolean = true) => {
      routeData.value = routes
      const routeLists = cloneDeep(routes)
      const menuRouter = formatRoutes(routeLists)
      if (isfirst) {
        menuList.value = [...menuRouter, ...constantMenuRoutes]
      }
      menuList.value.forEach(item => {
        router.addRoute('layout', item)
      })
      isGetRouter.value = true
    }

    // 获取路由信息
    const getRouteData = (): Routes.RouterListItem[] => {
      return [...routeData.value]
    }

    return { routeData, isGetRouter, menuList, formatRoutes, setRoutes, getRouteData }
  },
  {
    persist: [
      {
        paths: ['routeData', 'menuList'],
        storage: localStorage
      }
    ]
  }
)
